package net.luoran.dvm.common.util;

import cn.hutool.core.codec.Base62;
import cn.hutool.crypto.SecureUtil;

/**
 * @author ：M1nG
 * @date ：Created in 2020/11/12 10:31
 * @description： 密文工具
 * @version: 1.0
 */
public class CiphertextUtil {

    private String key = SecureUtil.md5("data_view");
    private Boolean b = true;

    public CiphertextUtil(String key) {
        if (key != null && !"".equals(key.trim())) {
            this.key = SecureUtil.md5(key);
        }
    }

    public CiphertextUtil() {

    }

    public void setKey(String key) {
        this.key = SecureUtil.md5(key);
    }

    /**
     * 加密
     *
     * @return
     */
    public String encrypt(String text) {
        String s = getCutString(this.key, 10, this.b) + Base62.encode(text) + getCutString(key, 10, !b);
        String ciphertext = new StringBuilder(s).reverse().toString();
        return ciphertext;
    }

    /**
     * 解密
     *
     * @return
     */
    public String decrypt(String ciphertext) {
        String s1 = new StringBuilder(ciphertext).reverse().toString();
        String substring = s1.substring(10, s1.length() - 10);
        String text = Base62.decodeStr(substring);
        return text;
    }

    /**
     * 解密
     *
     * @param str
     * @param size 获取的数量
     * @param rule true 正序 false
     * @return
     */
    public static String getCutString(String str, int size, boolean rule) {
        String[] split = str.split("");
        StringBuilder sb = new StringBuilder();
        if (rule) {
            for (int i = 0; i < split.length; i++) {
                sb.append(split[i]);
                if (sb.length() == size) {
                    break;
                }
            }
        } else {
            for (int i = split.length - 1; i >= 0; i--) {
                sb.append(split[i]);
                if (sb.length() == size) {
                    break;
                }
            }
        }
        return sb.toString();
    }


}
